﻿using QFramework;
using UnityEngine;

namespace GameJamLight
{
    public interface ICameraSystem : ISystem
    {
        void SetTarget(Transform target);
        void SetRange(float left, float right, float up, float down);
    }
    public class CameraSystem : AbstractSystem, ICameraSystem
    {
        private Transform mTarget;
        private Transform mCamera;
        private Vector3 mTempPos;
        private float left = -50, right = 50, up = 50, down = -50;
        private float mSmoothSpeed = 3;

        protected override void OnInit()
        {
            mTempPos.z = -10;
        }
        private void CameraFollow()
        {
            if (mTarget == null) return;
            mTempPos.x = Mathf.Clamp(mTarget.position.x, left, right);
            mTempPos.y = Mathf.Clamp(mTarget.position.y, down, up);
            if ((mCamera.position - mTempPos).sqrMagnitude < 0.01f) return;
            mCamera.localPosition = Vector3.Lerp(mCamera.position, mTempPos, mSmoothSpeed * Time.deltaTime);
        }

        void ICameraSystem.SetTarget(Transform target)
        {
            if (mTarget == null)
            {
                mCamera = Camera.main.transform;
                PublicMono.Instance.OnLateUpdate += OnUpdate;
            }
            if (target == null)
            {
                PublicMono.Instance.OnLateUpdate -= OnUpdate;
            }
            else
            {
                mTarget = target;
            }            
        }
        private void OnUpdate()
        {
            CameraFollow();
        }

        void ICameraSystem.SetRange(float left, float right, float up, float down)
        {
            this.left = left;
            this.right = right;
            this.up = up;
            this.down = down;
        }
    }
}